package com.fruit.util;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

import org.apache.commons.lang3.StringUtils;

/*
 '微信支付服务器签名支付请求请求类
 '============================================================================
 '*/
public class RequestHandler {
	
	private String key;
	
	protected Map<String, String> parameters;
	
	public RequestHandler(){
		parameters = new TreeMap<String, String>();
	}
	
	public void setParameters(String key, String value){
		if(StringUtils.isNoneEmpty(key)){
			parameters.put(key, value);
		}
	}
	
	public void createSign(){
		StringBuffer sb = new StringBuffer();
		Set<Entry<String,String>> es = parameters.entrySet();
		Iterator<Entry<String,String>> it = es.iterator();
		while(it.hasNext()){
			Map.Entry<String, String> entry = it.next();
			String k = entry.getKey();
			String v = entry.getValue();
			if(StringUtils.isNotEmpty(v) && !"sign".equals(k)
					&& !"key".equals(k)){
				sb.append(k).append("=").append(v).append("&");
			}
		}
		sb.append("key=").append(key);
		String sign = MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
		
		this.setParameters("sign", sign);
		
	}
	
	public String createSign(Map<String, String> params){
		StringBuffer sb = new StringBuffer();
		Set<Entry<String,String>> es = params.entrySet();
		Iterator<Entry<String,String>> it = es.iterator();
		while(it.hasNext()){
			Map.Entry<String, String> entry = it.next();
			String k = entry.getKey();
			String v = entry.getValue();
			if(StringUtils.isNotEmpty(v) && !"sign".equals(k)
					&& !"key".equals(k)){
				sb.append(k).append("=").append(v).append("&");
			}
		}
		sb.append("key=").append(key);
		String sign = MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
		return sign;
	}
	
	public String parseXML(){
		createSign();
		return CommonUtil.map2xmlBody(parameters, "xml");
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}
	
	
}